<template>
  <div class="container basicInfo">
    <table style="width: 100%" border="1" cellspacing="0" cellpadding="0" align="center">
				<!-- <tr>
					<td style="letter-spacing: 5px;">报告编号：</td>
					<td colspan="3">{{ basicForm.reportNumber }}</td>
				</tr> -->

				<tr>
					<td class="text-justify">设备名称</td>
					<td colspan="3"><el-input data-cusValidate="text" v-model="basicForm.equipmentName" style="width: 100%;"/></td>
				</tr>

				<tr>
					<td class="text-justify">设备型号</td>
					<td><el-input data-cusValidate="text" v-model="basicForm.specificationModel" style="width: 100%"/></td>
					<td class="text-justify">设备编号</td>
					<td><el-input data-cusValidate="text" v-model="basicForm.equipmentNumber" style="width: 100%"/></td>
				</tr>

				<tr>
					<td class="text-justify">生产单位</td>
					<td><el-input data-cusValidate="text" v-model="basicForm.manufacturerName" style="width: 100%"/></td>
					<td class="text-justify">设备场所</td>
					<td><el-input data-cusValidate="text" v-model="basicForm.usePlace" style="width: 100%"/></td>
				</tr>

				<tr>
					<td width="12%" class="text-justify">受检单位</td>
					<td width="40%">
						<el-input data-cusValidate="text" v-model="basicForm.entrustOrganizationName" style="width: 100%"/>
					</td>
					<!-- <td width="12%" class="text-justify">受检单位陪同人</td> -->
					<!-- <td width="40%"><el-input data-cusValidate="text" v-model="basicForm.entrustOrganizationAccompanyPerson" style="width: 100%"/></td> -->
					<td class="text-justify">检测时间</td>
					<td>
						<el-date-picker
							v-model="basicForm.detectionTime"
							type="date"
							value-format="yyyy-MM-dd"
							placeholder="选择日期">
						</el-date-picker>
					</td>
				</tr>

        <tr>
          <td width="12%" class="text-justify">委托单位</td>
          <td colspan="3">
            <el-input data-cusValidate="text" v-model="basicForm.delegationOrganizationName" style="width: 100%"/>
          </td>
        </tr>

				<tr>
					<td width="12%" class="text-justify">合同编号</td>
					<td><el-input data-cusValidate="text" v-model="basicForm.agreementNumber" style="width: 100%"/></td>
					<td class="text-justify">报告编号</td>
					<td><el-input data-cusValidate="text" v-model="basicForm.reportNumber" style="width: 100%"/></td>
				</tr>

				<tr>
					<td class="text-justify">单位地址</td>
					<td colspan="3">
						<el-input data-cusValidate="text" v-model="basicForm.entrustOrganizationAddress" style="width: 100%"/>
					</td>
					<!-- <td class="text-justify">设备台数</td>
					<td><el-input data-cusValidate="text" v-model="basicForm.equipmentMainArgs" style="width: 100%"/></td> -->
				</tr>

				<!-- <tr>
					<td class="text-justify">设备参数</td>
					<td>
						<el-input style="width: 80px;" v-model="basicForm.tubeCurrent"/>mA；
						<el-input style="width: 80px;" v-model="basicForm.tubeVoltage"/>kV
					</td>
					<td class="text-justify">出厂日期</td>
					<td>
						<el-date-picker
							v-model="basicForm.factoryDate"
							type="date"
							value-format="yyyy-MM-dd"
							placeholder="选择日期">
						</el-date-picker>
					</td>
				</tr> -->

        <tr v-if="basicForm.isEnvironmentDetection == 1">
					<td class="text-justify">项目类型</td>
          <td colspan="3">
            <el-radio-group style="margin-left: 10px;" v-model="basicForm.projectType">
              <el-radio :label="0">环境本底检测</el-radio><br />
              <el-radio :label="1">Ⅰ类</el-radio>
              <el-radio :label="2">Ⅱ类</el-radio>
              <el-radio :label="3">Ⅲ类 射线装置辐射环境检测</el-radio><br />
              <el-radio :label="4">Ⅰ类</el-radio>
              <el-radio :label="5">Ⅱ类</el-radio>
              <el-radio :label="6">Ⅲ类</el-radio>
              <el-radio :label="7">Ⅳ类</el-radio>
              <el-radio :label="8">Ⅴ类 放射源辐射环境检测</el-radio>
            </el-radio-group>
          </td>
        </tr>
				<tr>
					<td class="text-justify">检测类别</td>
					<td colspan="3">
            <div style="display: flex; align-items: center; justify-content: center;" v-if="basicForm.largeCategory == '3' || inspectionListCom.length == 0">
							<el-checkbox checked disabled >防护检测</el-checkbox>
              <!-- <el-checkbox-group class="inspectionTypeCheckbox" v-model="basicForm.inspectionFHTypeIdList" @change="handlerInspecFHTypeIdChange">
								<el-checkbox label="3">防护检测</el-checkbox>
							</el-checkbox-group> -->
							<el-radio-group style="margin-left: 10px;" v-model="basicForm.inspectionOTTypeIdList">
								<el-radio label="5" data-must="1">验收检测</el-radio>
								<el-radio label="8" data-must="1">委托检测</el-radio>
                <el-radio label="2" data-must="1">状态检测</el-radio>
							</el-radio-group>
              <el-checkbox v-model="basicForm.isProtectionCheck" :true-label="1" :false-label="0" @change="refreshTab = true">核查报告</el-checkbox>
              <el-checkbox v-model="basicForm.isEnvironmentDetection" :true-label="1" :false-label="0" @change="refreshTab = true">环境检测</el-checkbox>
						</div>
						<div style="display: flex; align-items: center; justify-content: center;" v-else>
							<el-checkbox-group class="inspectionTypeCheckbox" v-model="basicForm.inspectionFHTypeIdList" @change="handlerInspecFHTypeIdChange">
								<el-checkbox label="3">防护检测</el-checkbox>
							</el-checkbox-group>
							<el-radio-group style="margin-left: 10px;" v-model="basicForm.inspectionOTTypeIdList" @change="handlerInspecOTTypeIdChange">
								<el-radio label="5" data-must="1">验收检测</el-radio>
								<el-radio label="2" data-must="1">状态检测</el-radio>
                <el-radio label="4" data-must="1">
                  稳定性检测
                  <div style="display: inline-block;" v-show="basicForm.inspectionOTTypeIdList == 4">
                    (稳定性周期:
                    <el-select style="width: 100px;" v-model="basicForm.stabilityCycle">
                      <el-option
                        v-for="item in dict.type.stability_cycle"
                        :key="item.value"
                        :label="item.label"
                        :value="Number(item.value)"
                      ></el-option>
                    </el-select>)
                  </div>
                </el-radio>
							</el-radio-group>
              <el-checkbox v-model="basicForm.isEntrustDetection" :true-label="1" :false-label="0" @change="refreshTab = true">委托检测</el-checkbox>
              <el-checkbox v-model="basicForm.isProtectionCheck" :true-label="1" :false-label="0" @change="refreshTab = true">核查报告</el-checkbox>
              <el-checkbox v-model="basicForm.isEnvironmentDetection" :true-label="1" :false-label="0" @change="refreshTab = true">环境检测</el-checkbox>
						</div>
					</td>
				</tr>

				<tr>
					<td class="text-justify">检测项目</td>
					<td colspan="3">
						<el-checkbox-group
              v-model="basicForm.inspectionItemList"
              @change="(value) => {
                showLoading = true;

                if (!value || value.length == 0) return;
                const lastV = value[value.length - 1];
                if (lastV == '2') {
                  basicForm.inspectionItemList = value.includes('1') ? ['1', '2'] : ['2']
                } else if (lastV == '3') {
                  basicForm.inspectionItemList = value.includes('1') ? ['1', '3'] : ['3']
                }
              }"
            >
              <template v-if="
                activeNameEquipment == 'envir' &&
                (basicForm.basicInfoCode == '25' ||
                basicForm.basicInfoCode == '26')
                "
              >
                <el-checkbox label="4">辐射环境检测</el-checkbox>
              </template>

              <template v-else>
							  <el-checkbox label="1">质量控制检测</el-checkbox>
            	  <el-checkbox label="2">
                  <span v-if="
                    basicForm.qualityControlCodes.includes('70') ||
                    (basicForm.protectionDetectionVo && basicForm.protectionDetectionVo.qualityControlCodes.includes('70')) ||
                    (basicForm.environmentDetectionVo && basicForm.environmentDetectionVo.qualityControlCodes.includes('70')) ||
                    (basicForm.cbctDetectionVo && basicForm.cbctDetectionVo.qualityControlCodes.includes('70'))
                  ">工业探伤工作场所防护检测</span>
                  <span v-else>工作场所辐射防护检测</span>
                </el-checkbox>
            	  <el-checkbox label="3">工作场所放射防护检测</el-checkbox>
              </template>
						</el-checkbox-group>
					</td>
				</tr>

				<tr>
					<td class="text-justify">检测依据</td>
					<td colspan="3">
						<div class="standard" v-if="basicForm.standard">
							<el-checkbox style="display: block" v-for="(item, index) in basicForm.standard.defaultStandard" v-model="item.select" :key="index" @change="showLoading = true;">{{item.name}}</el-checkbox>
							<div style="width: 100%; text-align: left; margin-top: 10px; display: flex; align-items: center;">
								<span>其他：</span>
								<el-select
									v-model="basicForm.standard.vm_otherStandardList"
									:placeholder="lrstatus == '3' ? '' : '请选择'"
									style="width: 93%; display: inline-block"
									class="inputborder"
									:collapse-tags="lrstatus != '3'"
									multiple
									@change="showLoading = true;">
									<el-option
										:label="item.standardName"
										:value="item.standardId"
										v-for="(item,index) in inspectionStandardSelect"
										:key="index">
									</el-option>
								</el-select>
							</div>
						</div>
					</td>
				</tr>

        <tr>
					<td class="text-justify">评价依据</td>
					<td colspan="3">
						<div class="standard" v-if="basicForm.evaluateStandard">
							<el-checkbox style="display: block" v-for="(item, index) in basicForm.evaluateStandard.defaultStandard" v-model="item.select" :key="index" @change="showLoading = true;">{{item.name}}</el-checkbox>
							<div style="width: 100%; text-align: left; margin-top: 10px; display: flex; align-items: center;">
								<span>其他：</span>
								<el-select
									v-model="basicForm.evaluateStandard.vm_otherStandardList"
									:placeholder="lrstatus == '3' ? '' : '请选择'"
									style="width: 93%; display: inline-block"
									class="inputborder"
									:collapse-tags="lrstatus != '3'"
									multiple
									@change="showLoading = true;">
									<el-option
										:label="item.standardName"
										:value="item.standardId"
										v-for="(item,index) in inspectionStandardSelect"
										:key="index">
									</el-option>
								</el-select>
							</div>
						</div>
					</td>
				</tr>
			</table>

			<div class="equipmenttitle">
				一、基本情况
			</div>
			<basicIndex :basicForm="basicForm" :lrstatus="lrstatus" @updateSuccess="updateSuccess"></basicIndex>

			<div class="equipmenttitle" style="display: flex; justify-content: space-between; align-items: center">
				二、检测仪器
        <el-button style="height: 36px" type="primary" @click="handleResetComputed">重新计算</el-button>
			</div>

			<table style="width: 100%" border="1" cellspacing="0" cellpadding="0" align="center">

				<tr>
					<td width="100px">仪器名称</td>
					<td width="200px">编号</td>
					<td>校定/校准证书编号</td>
					<td width="190px">维护保养</td>
					<td width="80px">技术参数</td>
					<td width="70px">状态</td>
				</tr>

				<tr v-for="(item, index) in basicForm.instrumentationObject" :key="index">
					<!-- 仪器名称 -->
					<td style="text-align: left;">
						<el-checkbox v-model="item.isChecked">
							{{item.name}}<br/>
							<!-- （型号/规格：<el-input disabled v-model="item.equipmentTypeNumber" style="width: 100px"/>） -->
							（型号/规格：{{item.equipmentTypeNumber}}）
						</el-checkbox>
						<br>{{item.remark}}
					</td>

					<!-- 编号 -->
					<td>
						<el-select
							v-model="item.equipmentId"
							class="inputborder select"
							:class="lrstatus != '3' && 'ellipsis'"
							clearable
							@change="changeEquipment($event, item.equipmentList, item)"
							@visible-change="getEquipmentList($event, item)"
							:placeholder="lrstatus == '3' ? '' : '请选择'">
							<el-option
								v-for="it in item.equipmentList"
								:key="it.equipmentId"
								:label="it.equipmentNumber"
								:value="it.equipmentId">
							</el-option>
						</el-select>
					</td>

					<!-- 检定/校准证书编号 -->
					<td>
						<el-select
							v-model="item.vm_cerIdList"
							class="inputborder select"
							style="width: 100%"
							:placeholder="lrstatus == '3' ? '' : '请选择'"
							:collapse-tags="lrstatus != '3'"
							multiple>
							<el-option
								v-for="it in item.certificateList"
								:key="it.equipmentCertificateId"
								:label="it.certificateTypeName + '-' +it.certificateNumber"
								:value="it.equipmentCertificateId">
							</el-option>
						</el-select>
					</td>

					<!-- 维护保养 -->
					<td style="text-align: left;">
            <el-radio-group v-model="item.maintenance">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
              <el-radio :label="3">充电</el-radio>
              <br />
              <el-radio :label="2">清洁仪器外壳</el-radio>
            </el-radio-group>
					</td>

					<!-- 技术参数 -->
					<td>
						{{ item.technicalParameter }}
					</td>

					<!-- 状态 -->
					<td>正常</td>
				</tr>

				<tr v-if="basicForm.instrumentationOtherObject">
					<td colspan="5">
						<div style="display: flex; align-items: flex-start;">
							<el-checkbox v-model="basicForm.instrumentationOtherObject.isChecked"></el-checkbox>
							<span style="margin-left: 15px; text-align: left;">其他检测器具：{{ basicForm.instrumentationOtherObject.content }}</span>
						</div>
					</td>
					<td>正常</td>
				</tr>
			</table>

			<div class="tip-30">
				特殊情况说明：<el-input resize="none" :autosize=" {minRows: 2}" type="textarea" v-model="basicForm.specialCircumstances"/>
			</div>

			<div class="tip-30">
				检测结论：<el-input resize="none" :autosize=" {minRows: 2}" type="textarea" v-model="basicForm.conclusion"
         @blur="$bus.$emit('update-basicinfo', basicForm.taskDetectionEquipmentResultId)"/>
			</div>

			<div style="width: 100%; height: 200px; display: flex; margin-top: 20px;">
				<div style="width: 40%;">
					<div>
						<span style="font-weight: bold;">检测拍照：</span>
						<span v-if="!basicForm.sitePhotos">无</span>
						<imageUpload :limit="2" :isShowTip="false" v-model="basicForm.sitePhotos" @input="handleChangeSitePhotos"/>
					</div>
					<!-- <el-image
						v-if="basicForm.siteOssIdUrl"
						style="width: 100px; height: 100px"
						:src="basicForm.siteOssIdUrl[0]"
						:preview-src-list="basicForm.siteOssIdUrl">
					</el-image> -->
				</div>
				<div style="width: 50%; position: relative;">
					<div>
						<span style="font-weight: bold;">陪同人签名：</span>
						<span v-if="!basicForm.signOssId">无</span>
					</div>
					<div style="position: absolute; bottom: 0; right: 0;">
						<el-button type="primary" @click="handleOpenSign">签 名</el-button>
					</div>
					<el-image
						v-if="basicForm.signOssIdUrl"
						style="width: 400px;"
						:src="basicForm.signOssIdUrl"
						:preview-src-list="[basicForm.signOssIdUrl]">
					</el-image>
				</div>
			</div>

			<div class="copyright">
				委托单位对本次检测内容和检测结果无异议。
			</div>

		<!-- 手写弹框 -->
		<el-dialog
			title="手写签名"
			class="config-dialog"
			:visible.sync="signVisible"
			:close-on-click-modal="false"
			v-dialogDrag="true"
			append-to-body
			width="900px"
			@close="closehands"
		>
			<div class="showcode">
				<span class="title">扫码签名</span>
				<div ref="qrCodeDiv" class="qrCodeDiv">
				</div>
				<div class="trangle"></div>
			</div>

			<div class="content">
				<div v-if="signVisible" id="signSure" class="signSure">
					<canvas class="whiteBord" id="whiteBord" :style="imageUrlT && 'visibility: hidden'">
					</canvas>
					<img v-if="imageUrlT" :src="imageUrlT" alt="" :draggable="false" class="whiteBord img">
					<div class="btnBox">
						<div class="colorBox">
							<div class="color"
								v-for="(item, index) in colorList"
								:key="index"
								@click="changeColor(index)"
								:class="selected == index && 'selected'"
								:style="`background: ${item}`">
							</div>
						</div>
						<font-size className="pc" @change="handleChangeSlider" />
						<button class="primaryBtn" id="againWrite">重写</button>
						<button class="primaryBtn activeBtn" id="sureWrite">确定</button>
					</div>
				</div>
			</div>
		</el-dialog>
  </div>
</template>
<script>
import basicIndex  from './basicIndex'

import { updateBasicInfo, getResultInfo, resetComputed } from '@/api/testItem/detectionResult'
import { inspectionStandardListing } from '@/api/basicData/inspectionStandard'
import { equipmentCertificateListing } from '@/api/resourse/equipmentCertificate'
import { equipmentListAll } from '@/api/equipment/equipment'
import { listingBindEquipment } from '@/api/resourse/equipment'
import FontSize from '@/views/system/user/components/fontSize'
import {signature, changeOri} from "@/views/system/user/signature";
import QRCode from 'qrcodejs2';
import { upload2} from "@/api/basicData/seal";

export default {
  components: {
    basicIndex,
		FontSize
  },
  dicts: ['stability_cycle'],
  data() {
    return {
			// 检测标准下拉框
			inspectionStandardSelect: [],

			signVisible: false,
			ws: null,
			imageUrlT: null,
			colorList: ["#000", 'red', 'blue'], /* 颜色列表 */
			selected: 0, /* 选中的颜色 */

			updateTimer: null,
			showLoading: false,
			refreshTab: false,
      refreshBase: false,
    };
  },
  props: {
		// tab栏
    activeNameEquipment: {
			type: String,
      default: "0",
    },
		// 基本信息数据
    basicForm: {
			type: Object,
      default: () => {
				return {}
			},
    },
		// 状态
    lrstatus: {
			type: String,
      default: "",
    },
		// 检测类型
    inspectionList: {
			type: Array,
      default: () => {
				return []
			},
    },
  },
  computed:{
    inspectionListCom(){
			// 去除常规检测和稳定性检测
      return this.inspectionList.filter(item => item.inspectionTypeId != 1 && item.inspectionTypeId != 4)
    }
  },
  created() {
		this.updateSuccess()
		// 获取检测标准下拉框
		inspectionStandardListing({}).then(response => {
			this.inspectionStandardSelect = response.data;
		})

		this.$bus.$on('update-basicinfo', (taskDetectionEquipmentResultId) => {
			if (this.basicForm.taskDetectionEquipmentResultId == taskDetectionEquipmentResultId) {
				this.submitBasicForm()
			}
		})
		this.$bus.$on('update-protection-basicinfo', (taskDetectionEquipmentResultId) => {
			if (this.basicForm.protectionDetectionVo.taskDetectionEquipmentResultId == taskDetectionEquipmentResultId) {
				this.submitBasicForm(this.basicForm.protectionDetectionVo)
			}
		})
		this.$bus.$on('update-environment-basicinfo', (taskDetectionEquipmentResultId) => {
			if (this.basicForm.environmentDetectionVo.taskDetectionEquipmentResultId == taskDetectionEquipmentResultId) {
				this.submitBasicForm(this.basicForm.environmentDetectionVo)
			}
		})
		this.$bus.$on('update-cbctdetection-basicinfo', (taskDetectionEquipmentResultId) => {
			if (this.basicForm.cbctDetectionVo.taskDetectionEquipmentResultId == taskDetectionEquipmentResultId) {
				this.submitBasicForm(this.basicForm.cbctDetectionVo)
			}
		})
  },
  destroyed() {
    let inputs = document.getElementsByClassName('basicInfo')[0]?.getElementsByTagName("input");
    if(inputs){
      for (let i = 0; i < inputs.length; i++) {
        this.unbind(inputs[i])
      }
    }
  },
  methods: {
    updateSuccess(){
      this.$nextTick(()=>{
        setTimeout(()=>{
          let inputs = document.getElementsByClassName('basicInfo')[0].getElementsByTagName("input");
          for (let i = 0; i < inputs.length; i++) {
          	this.bind(inputs[i], () => {
          		this.submitBasicForm()
          	}, 1)
          }
          let textarea = document.getElementsByTagName("textarea")[0];
					if (textarea) {
						textarea.onchange = (e) => {
							this.submitBasicForm();
						}
					}
        },500);

      })
    },
    // 提交基础信息
    submitBasicForm(form) {
			if (this.updateTimer || localStorage.getItem('FS_updateBasicForming') == '1') {
				clearTimeout(this.updateTimer);
				this.updateTimer = null
			}
			this.updateTimer = setTimeout(() => {
				let basicForm = {}
				if (!form) {
					basicForm = JSON.parse(JSON.stringify(this.basicForm))
				} else {
					basicForm = JSON.parse(JSON.stringify(form))
				}
				if (this.lrstatus == "3") {
					return;
				}
				this.$emit("loadingchange", true);
				let arr = []; /* 其他检测标准 */
        let arr2 = []; /* 其他检测标准 */
				let findobj;
				let findobj2;
				basicForm.resultId = basicForm.taskDetectionEquipmentResultId
				basicForm.standard && basicForm.standard.vm_otherStandardList && basicForm.standard.vm_otherStandardList.forEach(id => {
					findobj = this.inspectionStandardSelect.find(item => item.standardId == id);
					if(findobj) {
						arr.push({
							id: id,
							name: findobj.standardName
						})
					}
				})
        basicForm.evaluateStandard && basicForm.evaluateStandard.vm_otherStandardList && basicForm.evaluateStandard.vm_otherStandardList.forEach(id => {
					findobj2 = this.inspectionStandardSelect.find(item => item.standardId == id);
					if(findobj2) {
						arr2.push({
							id: id,
							name: findobj2.standardName
						})
					}
				})
				if(basicForm.basicInfoCode == '12') {
					basicForm.basicInfo.otherType = basicForm.basicInfo.cus_otherTarget + "/" + basicForm.basicInfo.cus_otherfiltration;
				}
				basicForm.standard && (basicForm.standard.otherStandard = arr);
				basicForm.evaluateStandard && (basicForm.evaluateStandard.otherStandard = arr2);
				let copyBasicForm = JSON.parse(JSON.stringify(basicForm));
				copyBasicForm.basicInfo = JSON.stringify(copyBasicForm.basicInfo);
				copyBasicForm.instrumentationObject.forEach(item => { /* 生成证书列表certificateEntities */
					let arr = [];
					item.vm_cerIdList?.forEach(id => {
						let findobj = item.certificateList?.find(it => id == it.equipmentCertificateId);
						if (findobj) {
							arr.push({
								equipmentCertificateId: findobj.equipmentCertificateId,
								certificateTypeCode: findobj.certificateTypeCode,
								certificateNumber: findobj.certificateNumber,
								certificateValidity: findobj.certificateValidity,
								institutionName: findobj.institutionName,
							})
						}
					})
					item.certificateEntities = arr;
				})
				copyBasicForm.inspectionItem = copyBasicForm.inspectionItemList.join(',')
				if (copyBasicForm.inspectionFHTypeIdList?.length > 0) {
					copyBasicForm.inspectionTypeId = copyBasicForm.inspectionFHTypeIdList.join(',') + ',' + copyBasicForm.inspectionOTTypeIdList
				} else {
					copyBasicForm.inspectionTypeId = copyBasicForm.inspectionOTTypeIdList
				}
        if (copyBasicForm.isEntrustDetection == '1') {
          copyBasicForm.inspectionTypeId = copyBasicForm.inspectionTypeId + ',8'
        }
				localStorage.setItem('FS_updateBasicForming', '1')
				if (this.showLoading) {
					this.$modal.loading('数据保存中...')
					this.showLoading = false
				}
				updateBasicInfo(copyBasicForm).then((response) => {
					this.basicForm.reportNumber = response.data.reportNumber || this.basicForm.reportNumber
					this.$modal.closeLoading()
					this.$emit("loadingchange", false);
          localStorage.setItem('FS_updateBasicForming', '0')
          if (this.refreshBase) {
						this.refreshBase = false
            getResultInfo(this.basicForm.taskResultId).then(res => {
              if (this.activeNameEquipment == '0') { // 基本信息
                this.$set(this.basicForm.standard, 'vm_otherStandardList', res?.data?.standard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.standard, 'defaultStandard', res?.data?.standard?.defaultStandard)
                this.$set(this.basicForm.evaluateStandard, 'vm_otherStandardList', res?.data?.evaluateStandard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.evaluateStandard, 'defaultStandard', res?.data?.evaluateStandard?.defaultStandard)
              } else if (this.activeNameEquipment == 'index') { // 防护基本信息
                this.$set(this.basicForm.standard, 'vm_otherStandardList', res?.data?.protectionDetectionVo?.standard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.standard, 'defaultStandard', res?.data?.protectionDetectionVo?.standard?.defaultStandard)
                this.$set(this.basicForm.evaluateStandard, 'vm_otherStandardList', res?.data?.protectionDetectionVo?.evaluateStandard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.evaluateStandard, 'defaultStandard', res?.data?.protectionDetectionVo?.evaluateStandard?.defaultStandard)
              } else if (this.activeNameEquipment == 'envir') { // 环境检测基本信息
                this.$set(this.basicForm.standard, 'vm_otherStandardList', res?.data?.environmentDetectionVo?.standard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.standard, 'defaultStandard', res?.data?.environmentDetectionVo?.standard?.defaultStandard)
                this.$set(this.basicForm.evaluateStandard, 'vm_otherStandardList', res?.data?.environmentDetectionVo?.evaluateStandard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.evaluateStandard, 'defaultStandard', res?.data?.environmentDetectionVo?.evaluateStandard?.defaultStandard)
              } else if (this.activeNameEquipment == 'cbct') { // CBCT检测基本信息
                this.$set(this.basicForm.standard, 'vm_otherStandardList', res?.data?.cbctDetectionVo?.standard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.standard, 'defaultStandard', res?.data?.cbctDetectionVo?.standard?.defaultStandard)
                this.$set(this.basicForm.evaluateStandard, 'vm_otherStandardList', res?.data?.cbctDetectionVo?.evaluateStandard?.otherStandard?.map(item => item.id) || [])
                this.$set(this.basicForm.evaluateStandard, 'defaultStandard', res?.data?.cbctDetectionVo?.evaluateStandard?.defaultStandard)
              }
            }).catch(err => {})
					}
					if (this.refreshTab) {
						this.$bus.$emit('refreshTabList')
						this.refreshTab = false
					}
				}).catch((response) => {
					this.$modal.closeLoading()
					this.$emit("loadingchange", true);
          localStorage.setItem('FS_updateBasicForming', '0')
				});
			}, 1000)
    },
		// 根据仪器获取编号
		async getEquipmentList(visible, item) {
			if (!visible) return
			let { code, data } = await equipmentListAll({
				instrumentTypeCode: item.code
			})
			if (code != 200) return
			this.$set(item, 'equipmentList', data)
		},
		// 更改设备编号
		changeEquipment(value, equipmentList, row) {
			let findobj = equipmentList.find(item => value == item.equipmentId)
			if (!findobj) {
				this.$set(row, 'technicalParameter', '')
				this.$set(row, 'maintenance', '')
				return
			}
			row.isChecked = true
			row.equipmentTypeNumber = findobj.equipmentTypeNumber
			row.equipmentName = findobj.equipmentName
			row.equipmentNumber = findobj.equipmentNumber
			row.technicalParameter = findobj.technicalParameter
			row.maintenance = findobj.maintenance

			equipmentCertificateListing(findobj.equipmentId).then((res) => {
			  this.$set(row, 'vm_cerIdList', [])
				this.$set(row, 'certificateList',  res.data || [])
				row.certificateTypes.forEach(code => {
					const findRes = row.certificateList?.find(it => it.certificateTypeCode == code)
					if (findRes) row.vm_cerIdList.push(findRes.equipmentCertificateId)
				})
				this.submitBasicForm()
			}).catch((err) => {})

			listingBindEquipment(value, true).then((res) => {
				const bindEquiomentList = res.data || []
				this.basicForm.instrumentationObject.forEach(item => {
					const findRes = bindEquiomentList.find(it => it.instrumentTypeCode == item.code)
					if (findRes) {
						item.isChecked = true
						item.equipmentTypeNumber = findRes.equipmentTypeNumber
						item.equipmentNumber = findRes.equipmentNumber

						const findRes2 = item.equipmentList.find(it => it.equipmentId == findRes.equipmentId)
						if (findRes2) {
							item.equipmentId = findRes2.equipmentId
							equipmentCertificateListing(item.equipmentId).then((res) => {
							  this.$set(item, 'vm_cerIdList', [])
								this.$set(item, 'certificateList', res.data || [])
								item.certificateTypes.forEach(code => {
									const findRes = item.certificateList?.find(it => it.certificateTypeCode == code)
									if (findRes) item.vm_cerIdList.push(findRes.equipmentCertificateId)
								})
								this.submitBasicForm()
							}).catch((err) => {})
						}
					}
				})
			}).catch((err) => {})
		},
		emitloadingchange(val) {
			this.$emit("loadingchange", val);
		},
		handleChangeSitePhotos(val) {
			this.submitBasicForm()
		},
		handleOpenSign() {
			this.signVisible = true;
			this.imageUrlT = null;
			const userId = this.$store.state.user.userInfo.userId
			this.$nextTick(() => {
				let params = {
					whiteBord:'whiteBord', //canvas标签的id名称
					againWrite:'againWrite', //重写按钮id名
					sureWrite:'sureWrite', //确认按钮id名
					maxFonts: 20,
					minFonts: 16,
					clearWriteCallback: () => { //重写的回调函数
						this.imageUrlT = null
					},
					sureWriteCallback: (imageBase64) => { //签名完成后的回调函数
						this.suresign(imageBase64, userId)
					},
				}
				signature(params);
				let VUE_APP_CONTEXT_PATH = process.env.VUE_APP_CONTEXT_PATH == '/' ? '' : process.env.VUE_APP_CONTEXT_PATH
				let url = "http://" + document.location.host + VUE_APP_CONTEXT_PATH + "/handsf?userId=" + userId;
				console.log("url", url);
				this.qrcode = new QRCode(this.$refs.qrCodeDiv, {
					text: url,
					width: 100,
					height: 100,
					colorDark: "#333333", //二维码颜色
					colorLight: "#ffffff", //二维码背景色
					correctLevel: QRCode.CorrectLevel.L //容错率，L/M/H
				})
				let prefixUrl = `ws://${document.location.host}${process.env.VUE_APP_BASE_API}/ws/signature/`;
				//创建WebSocket连接对象
				this.ws = new WebSocket(prefixUrl + userId);
				//连接成功建立
				this.ws.onopen = function (event) {
					console.log('建立连接', event)
				}
				//接收到消息
				this.ws.onmessage = (event) => {
					console.log('接收到内容：' + event.data);
					if (event.data) {
						this.$set(this, "imageUrlT", 'data:image/png;base64,' + event.data)
					}
				}
				//连接发生错误
				this.ws.onerror = function (event) {
					console.log('发生错误')
				}
				//连接关闭
				this.ws.onclose = function (event) {
					console.log('关闭连接')
				}
			})
		},
		handleChangeSlider(val) {
			changeOri('changeSize', null, {
				maxFonts: val,
				minFonts: val - 4
			})
		},
		// 签名完成
		suresign(imageBase64, userId) {
			let base64;
			if(this.imageUrlT) { /* 上传的图片 */
				base64 = this.imageUrlT;
			}else if(imageBase64 != "empty") { /* 绘制的图片 */
				base64 = imageBase64;
			}else {
				this.$modal.msgWarning("签名不能为空");
				return;
			}

			let blob =  this.dataURLtoBlob(base64);
			let file1 = this.blobToFile(blob, "handsfile");
			let fd = new FormData();
			fd.append("file", file1);
			this.$modal.loading('图片上传中');
			upload2(fd).then((response) => {
				this.$modal.closeLoading()
				this.$modal.msgSuccess("签名成功");
				this.signVisible = false;
				this.ws.close();
				this.basicForm.signOssId = response.data.ossId;
				this.basicForm.signOssIdUrl = response.data.url;
				this.submitBasicForm();
			}).catch(err => {
				this.$modal.closeLoading()
			});
		},
		// 将base64转换为blob
		dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    // 将blob转换为file
    blobToFile(theBlob, fileName){
       theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
       theBlob.name = fileName;                // 文件名
       return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
    },
		// 更改颜色
		changeColor(index) {
			this.selected = index;
			changeOri("changeColor", this.colorList[index]);
		},
		// 关闭手写弹框
		closehands() {
			let qrCodeDiv = document.getElementsByClassName("qrCodeDiv");
			qrCodeDiv[0].innerHTML = "";
			this.ws.close();
		},
		handlerInspecFHTypeIdChange(value) {
			this.refreshTab = true
			this.showLoading = true
			if (value.includes('3') && !this.basicForm.inspectionItemList.includes('2')) {
				this.basicForm.inspectionItemList.push('2')
			}
			if (!value.includes('3') && this.basicForm.inspectionItemList.includes('2')) {
				const index = this.basicForm.inspectionItemList.indexOf('2')
				this.basicForm.inspectionItemList.splice(index, 1)
			}
		},
		handlerInspecOTTypeIdChange(value) {
			this.showLoading = true
			if (value && !this.basicForm.inspectionItemList.includes('1')) {
				this.basicForm.inspectionItemList.push('1')
			}
			if (!value && this.basicForm.inspectionItemList.includes('1')) {
				const index = this.basicForm.inspectionItemList.indexOf('1')
				this.basicForm.inspectionItemList.splice(index, 1)
			}
		},
    // 重新计算
    handleResetComputed() {
      const taskDetectionEquipmentId = this.basicForm.taskDetectionEquipmentId
      resetComputed(taskDetectionEquipmentId).then(res => {
        this.$message.success('操作成功')
      }).catch(err => {})
    }
  },
  watch: {
    'basicForm.basicInfo.isIntraoral': {
      handler(val) {
        this.refreshBase = true
      },
      deep: true
    },
    'basicForm.basicInfo.isPanorama': {
      handler(val) {
        this.refreshBase = true
      },
      deep: true
    },
    'basicForm.basicInfo.isHeader': {
      handler(val) {
        this.refreshBase = true
      },
      deep: true
    },
    'basicForm.protectionDetectionVo.basicInfo.isHeader': {
      handler(val) {
        this.refreshBase = true
      },
      deep: true
    },
    'basicForm.basicInfo.isCbct': {
      handler(val) {
        this.refreshBase = true
      },
      deep: true
    },
    'basicForm.basicInfo.nuclideInfoList': {
      handler(val) {
        this.submitBasicForm()
      },
      deep: true
    },
  }
}
</script>
<style lang="scss" scoped>
@import './content.scss';

.config-dialog {
	::v-deep .el-dialog__body {
		padding: 0;
	}
}
.showcode {
	position: absolute;
	top: 7px;
	right: 118px;
	font-size: 16px;
	font-weight: bold;
	text-align: center;
	width: 108px;
	z-index: 1;
	cursor: pointer;
	.title {
		line-height: 50px;
		color: #3c3c3c;
	}
	&:hover {
		.qrCodeDiv {
			display: block;
		}
		.trangle {
			display: block;
		}
	}
	.qrCodeDiv {
    border: 1px solid #999;
    padding: 3px;
		// height: 0;
		display: none;
		transition: all .3s;
		margin-top: -3px;

	}
	.trangle {
		border-top: 7px solid transparent;
		border-right: 7px solid transparent;
		border-bottom: 7px solid #434343;
		border-left: 7px solid transparent;
		position: absolute;
		top: 33px;
		right: 48px;
		display: none;
	}
}
.content {
	height: 383px;
}
.signSure{
	border-radius: 16px;
	position: relative;
	.topTitle{
		margin: 20px 0 12px 12px;
		font-size: 16px;
	}
	.whiteBord{
		width: 100%;
		height: 300px;
		border-bottom: 1px solid #eee;
		margin: 0 auto;
		border-radius: 4px;
		cursor: pointer;
		&.img {
			position: absolute;
			top: 0;
			right: 0;
			cursor: not-allowed;
		}
	}
	.btnBox{
		padding: 20px 50px;
		display: flex;
		justify-content: space-between;
		.colorBox {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20px;
			.color {
				width: 18px;
				height: 18px;
				border-radius: 50%;
				margin-right: 10px;
				&:hover {
					cursor: pointer;
				}
			}
			.selected {
				transform: scale(1.3);
			}
		}
		.primaryBtn{
			width: 40%;
			height: 40px;
			color: #666;
			border: 1px solid #ccc;
			border-radius: 4px;
			background: #fff;
			cursor: pointer;
			transition: .4s cubic-bezier(.175, .885, .32, 1);
			transition-property: background, border, box-shadow, outline, opacity;
			&:hover {
				background-color: #dedede;
				border-color: #a1a1a1;
				box-shadow: 0 2px 1px rgba(0, 0, 0, .1);
			}
			&:nth-of-type(1) {
				margin-right: 30px;
			}
		}
		.activeBtn{
			background: #2A72EE;
			color: #fff;
			border: none;
			&:hover {
				background-color: #46a6ff;
			}
		}
	}
}
</style>
